<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
	<th:block th:include="include :: header('爬虫配置')"/>
	<style>
		.tbStyle{
			display: none;
		}
	</style>
</head>
<body>
<div class="layui-container">
	<form id="dataSourceForm" class="layui-form" style="margin-top: 20px;">
		<input type="hidden" id="rules" th:value="${s.rules}">
		<input type="hidden" name="id" th:value="${s.id}">
		<div class="layui-form-item">
			<label class="layui-form-label">爬虫名称</label>
			<div class="layui-input-block">
				<input type="text" name="spiderName" th:value="${s.spiderName}" value="" class="layui-input" lay-verify="required" autocomplete="off"/>
			</div>
		</div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">cron表达式</label>
                <div class="layui-input-inline">
                    <input type="text" name="cron" th:value="${s.cron}" class="layui-input" placeholder="mysql" lay-verify="required" autocomplete="off"/>
                </div>
            </div>
            <div class="layui-inline">
                <a class="layui-btn layui-btn-sm layui-bg-blue" onclick="openDig()">
                    <i class="layui-icon layui-icon-edit"></i>生成cron表达式
                </a>
            </div>
        </div>
		<div class="layui-form-item">
			<label class="layui-form-label">爬取地址</label>
			<div class="layui-input-block">
				<input type="text" name="uri" th:value="${s.uri}" class="layui-input" placeholder="url" lay-verify="required" autocomplete="off"/>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">是否启用</label>
			<div class="layui-input-block">
				<input type="radio" name="isUse" value="0" title="启用" th:checked="${s.isUse} eq 0">
				<input type="radio" name="isUse" value="1" title="未启用" th:checked="${s.isUse} eq 1" >
			</div>
		</div>

		<div class="layui-form-item">
			<div class="layui-input-block sourceBtn" style="text-align: right;" id="sourceBtn">
				<a class="layui-btn layui-btn-sm layui-bg-cyan" lay-submit="" lay-filter="test"><i class="layui-icon layui-icon-refresh-3"></i>测试运行</a>
				<a class="layui-btn layui-btn-sm layui-btn-normal" lay-submit="" lay-filter="save"><i class="layui-icon layui-icon-ok"></i>确定保存</a>
				<a class="layui-btn layui-btn-sm layui-btn-primary" data-method="close"><i class="layui-icon layui-icon-close"></i>取消关闭</a>
				<ul class="layui-nav layui-bg-red" lay-filter="node"
					style="border-radius: 2px;float: right;padding: 0px;margin-left: 12px">
					<li class="layui-nav-item" style="line-height: 30px;font-size: 14px">
						<a href="javascript:;" style="color: #fff;padding: 0px 30px 0px 20px;font-size: 12px">
							新建节点
							<span class="layui-nav-more" style="right: 10px;font-size: 12px"></span>
						</a>
						<dl class="layui-nav-child" style="top:30px">
							<dd><a href="#">开始爬取</a></dd>
							<dd><a href="#">定义变量</a></dd>
							<dd><a href="#">循环</a></dd>
							<dd><a href="#">内容输出</a></dd>
							<dd><a href="#">爬取详情页</a></dd>
						</dl>
					</li>
				</ul>
			</div>
		</div>
	</form>
</div>
<div class="layui-tab layui-tab-brief" lay-filter="tab" lay-allowClose=true>
	<ul class="layui-tab-title">

	</ul>
	<div class="layui-tab-content">

	</div>
</div>
<th:block th:include="include :: jquery"/>
<th:block th:include="include :: footer"/>
<script>
	var $,id=0,active,layer;
	layui.use(['form','element','table','layer'],function(){
		var form = layui.form,rules,table = layui.table,element = layui.element;
		$ = layui.jquery,layer = layui.layer;
		//layui自动执行方法
		layer.ready(function () {
			var rules = $('#rules').val();
			rules = JSON.parse(rules);
			$.each(rules,function (i,rule) {
				var idName = '',title = '',subtitle = '',html = '',
					variable = rule.variable,
					content = rule.contentVar,
					output = rule.output;

				if(variable){
					subtitle = '定义变量';
					html = $('#nodeVar').clone();

					//
					html.find('input[name="nName"]').attr('value',rule.nName);
					var tbody = html.find('table tbody');
					var trs = $(tbody).find('tr');
					for(var i=0;i<rule.variable.variableName.length-trs.length;i++){
						var tr = $(trs[0]).clone();
						$(tbody).append(tr);
					}
					trs = $(tbody).find('tr');
					$.each(trs,function (i,tr) {
						var tds = $(tr).find('td');
						$.each(tds,function (j,td) {
							var value = '';
							if(j==0){
								value = rule.variable.variableName[i];
							}else if(j==1){
								value = rule.variable.variableValue[i];
							}else if(j==2){
								value = rule.variable.variableDescription[i];
							}
							if(j<tds.length-1) {
								$(td).find('input').attr('value',value);
							}
						})
					});


				}
				else if(content){
					subtitle = '获取详情页';
					html = $('#content').clone();

					//进行对输入框赋值
					html.find('input[name="nName"]').attr('value',rule.nName);
					html.find('input[name="connect"]').attr('value',rule.connect);
					html.find('input[name="socket"]').attr('value',rule.socket);
					//下拉选择
					var options = html.find('select[name="method"]').find("option");
					$.each(options,function (i,option) {
						if($(option).attr("value") == rule.method){
							$(option).attr("selected",true);
						}
					});
					$.each(html.find('select[name="encoding"]').find("option"),function(i,option){
						if($(option).attr("value") == rule.encoding){
							$(option).attr("selected",true);
						}
					});

					html.find('input[name="nName"]').attr('value',rule.nName);
					var tbody = html.find('table tbody');
					var trs = $(tbody).find('tr');
					$.each(trs,function (i,tr) {
						var tds = $(tr).find('td');
						$(tds[0]).find('input').attr('value',rule.contentVar.variableName[i]);
						$(tds[1]).find('input').attr('value',rule.contentVar.variableValue[i]);
						$(tds[2]).find('input').attr('value',rule.contentVar.variableDescription[i]);
					});

				}
				else if(output){
					subtitle = '输出内容';
					html = $('#nodeOutput').clone();
					html.find('input[name="nName"]').attr('value',rule.nName);
					//输出方式
					var dialog = rule.style.dialog,database = rule.style.database;
					if(dialog){
						$(html.find('input[type="checkbox"]')[0]).attr('checked',true);
					}
					if(database){
						$(html.find('input[type="checkbox"]')[1]).attr('checked',true);

						//设置定时器
						setTimeout(function () {
							//表格隐藏列显示
							$('.tbStyle').show();
							//下拉选择框显示
							var id = rule.database,tableName = rule.tableName;
							dataSourceCheck(id,form);
							databaseSelect(id,form,tableName);
						},100);
					}

					var tbody = html.find('table tbody');
					var trs = $(tbody).find('tr');
					for(var i=0;i<rule.output.outputName.length - trs.length;i++){
						var tr = $(trs[0]).clone();
						$(tbody).append(tr);
					}
					trs = $(tbody).find('tr');
					$.each(trs,function(i,tr){
						var tds = $(tr).find('td');
						$(tds[0]).find('input').attr("value",rule.output.outputName[i]);
						$(tds[1]).find('input').attr("value",rule.output.outputColumn[i]);
						$(tds[2]).find('input').attr("value",rule.output.outputValue[i]);
					});
				}
				else{
					subtitle = '开始爬取';
					html = $('#nodeStart').clone();

					//进行对输入框赋值
					html.find('input[name="nName"]').attr('value',rule.nName);
					html.find('input[name="url"]').attr('value',rule.url);
					html.find('input[name="connect"]').attr('value',rule.connect);
					html.find('input[name="socket"]').attr('value',rule.socket);
					//下拉选择
					var options = html.find('select[name="method"]').find("option");
					$.each(options,function (i,option) {
						if($(option).attr("value") == rule.method){
							$(option).attr("selected",true);
						}
					});
					$.each(html.find('select[name="encoding"]').find("option"),function(i,option){
						if($(option).attr("value") == rule.encoding){
							$(option).attr("selected",true);
						}
					});


				}
				title = rule.nName?subtitle:rule.nName;
				id++;
				//添加tab
				element.tabAdd('tab',{
					title:title,
					content:html.html(),
					id:id
				});
				element.tabChange('tab',id);
				form.render();//刷新表单所有的控件

			})
		});

		//表单验证
		form.verify({

		});
		//监听菜单工具条
		element.on('nav(node)',function(elem){
			var text = elem.text();
			switch(text){
				case '开始爬取':
					active.addTabs(text,'nodeStart');
					form.render('select');
					break;
				case '定义变量':
					active.addTabs(text,'nodeVar');
					break;
				case '内容输出':
					active.addTabs(text,'nodeOutput');
					form.render();
					break;
				case '循环':
					active.addTabs(text,'loop');
					break;
				case '爬取详情页':
					active.addTabs(text,'content');
					form.render('select');
					break;
			}
		});
		//监听测试按钮
		form.on('submit(test)',function(data){
			var loading = layer.load(0,{
				shade:0.5
			});
			rules = getRules();

			var data = data.field;
			data.rules = JSON.stringify(rules);
			$.ajax({
				type:'post',
				url:'/sc/test',
				data:data,
				dataType:'json',
				success:function (result) {
					var style;
					$.each(rules,function (i,rule) {
						style = rule.style;
						if(style){
							return false;
						}else{
							style = false;
						}
					})

					if(style && style.dialog) {
						window.parent.openDialog(result);
					}if(style && style.database) {
						window.parent.openDialog(result);
					}
					layer.close(loading);
				}
			});
		});
		//监听保存按钮
		form.on('submit(save)',function(data){
			rules = getRules();
			var data = data.field;
			data.rules = JSON.stringify(rules);
			saveOrUpdate('/sc/addOrEdit','spiderTable',data,$);
		});

		form.on('checkbox(database)',function (data) {
			var b = data.elem.checked;//是否被选中
			if(b){
				var ck = data.elem;
				var div = $(ck).parent('div');
				dataSourceCheck('',form);
			}else{
				var ck = data.elem;
				var div = $(ck).parent('div');
				$.each($('#dataSource select'),function (i,s) {
					$.each($(s).find('option'),function (j,option) {
						$(option).remove();
					})
				})
				$('#dataSource').hide();//隐藏
				$('.tbStyle').hide();//隐藏
			}
			form.render('select');

		});
		form.on('select(database)',function (data) {
			var id = data.value;
			databaseSelect(id,form,'');
		});

		form.on('select(tableName)',function (data) {
			$('.tbStyle').show();//显示隐藏的内容
		});


		active = {
			addTabs:function(title,idName){
				id++;
				//添加tab的方法
				element.tabAdd('tab',{
					title:title,
					content:$('#'+idName).html(),
					id:id
				});
				element.tabChange('tab',id);
			},
			close:function(othis){
				//先获取当前iframe层的索引
				var index = parent.layer.getFrameIndex(window.name);
				parent.layer.close(index);//执行关闭
			},
			addVar:function(othis){
				var form = $(othis).parents("form");
				var tbody = $(form).find("table tbody");

				var tr = $(tbody).find("tr:first").clone();
				tr.find("td input").val("");
				$(tbody).append(tr);
			},
			addOut:function(othis){
				var form = $(othis).parents("form");
				var tbody = $(form).find("table tbody");

				var tr = $(tbody).find("tr:first").clone();
				tr.find("td input").val("");
				$(tbody).append(tr);
			}
		}

		$('#sourceBtn .layui-btn').on('click',function(){
			var othis = $(this),method = othis.data('method');
			active[method]?active[method].call(this,othis):"";
		});

		$('#varBtn .layui-btn').on('click',function(){
			var othis = $(this),method = othis.data('method');
			active[method]?active[method].call(this,othis):"";
		});
		$('#outBtn .layui-btn').on('click',function(){
			var othis = $(this),method = othis.data('method');
			active[method]?active[method].call(this,othis):"";
		});

	});

	function delRow(obj){
		$(obj).parents("tr").remove();
	}

	function  getRules() {
		var rules = [];
		//获取tabs下面的所有form表单
		var forms = $('.layui-tab').find('form');
		$.each(forms,function (i,form) {
			var formData = $(form).serializeJSON();
			var tbody = $(form).find("table tbody");
			if(tbody.length>0){
				var shape = $(tbody).attr('shape');
				var id = $(tbody).attr("id");
				var trs = $(tbody).find('tr');
				var v = {},o = {};
				if(shape == 'variable'){
					var vName=[],vValue=[],vDes=[];
					$.each(trs,function(i,tr){
						//获取每一行的td 下面的input
						var ins = $(tr).find('td input');
						if(ins.length>=3){
							vName.push($(ins[0]).val());//第一个输入框值，变量名
							vValue.push($(ins[1]).val());//第二个输入框值，变量值(公式)
							vDes.push($(ins[2]).val());//第三个输入框值， 描述
						}
					});
					v.variableName = vName;
					v.variableValue =vValue;
					v.variableDescription = vDes;//对象自定义属性且赋值
					if("varBody"==id) {
						formData.variable = v;
					}else{
						formData.contentVar = v;
					}
				}else if(shape == 'output'){
					var oName=[],oColumn=[],oValue=[];
					$.each(trs,function (i,tr) {
						var ins = $(tr).find('td input');
						if(ins.length>=2){
							oName.push($(ins[0]).val());
							oColumn.push($(ins[1]).val())
							oValue.push($(ins[2]).val());
						}
					});
					o.outputName = oName;
					o.outputColumn = oColumn;
					o.outputValue = oValue;

					formData.output = o;
				}

			}
			rules.push(formData);
		})
		return rules;
	}

	function dataSourceCheck(id,form){
		$('#dataSource').show();//显示
		$.ajax({//数据提交请求
			type:'post',
			url:'/dsc/find',
			data:{
				isUse:0
			},
			async:false,
			dataType: 'json',
			success:function (result) {
				var dsc = result.data;
				//获取第一个下拉框
				var fs = $('#dataSource select:first');
				fs.append(new Option("请选择数据库",""));
				$.each(dsc,function (i,d) {
					var dbName = d.dbName;
					fs.append(new Option(dbName,d.id,false,d.id==id?true:false));
				});
				form.render('select');
			}
		});
	}

	function databaseSelect(id,form,tableName){
		var s = $('#dataSource select')[1];
		$(s).empty();
		$(s).append(new Option("请选择表",""));
		if(id!=''){
			$.get('/dsc/getTableName/'+id,function (result) {
				$.each(result.data,function (i,table) {
					$(s).append(new Option(table,table,false,table==tableName?true:false));
				});
				form.render('select');
			});
		}
		form.render('select');

	}
    function openDig() {
        layer.open({
            type:2,
            content:'/tqc/editCron',
            area:['850px','100%'],
            offset:'c',

        });
    }

    function changeCron(value){
        $('input[name="cron"]').val(value);
    }
</script>
<div id="nodeStart" class="layui-container" style="display: none">
	<form class="layui-form">
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">节点名称</label>
				<div class="layui-input-inline">
					<input class="layui-input" name="nName" autocomplete="off">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<label class="layui-form-label">爬取地址</label>
			<div class="layui-input-block">
				<input class="layui-input" name="url" lay-verify="required" autocomplete="off">
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">请求方法</label>
				<div class="layui-input-inline">
					<select name="method">
						<option value="get">GET</option>
						<option value="post">POST</option>
					</select>
				</div>
			</div>
			<div class="layui-inline">
				<label class="layui-form-label">编码格式</label>
				<div class="layui-input-inline">
					<select name="encoding">
						<option value="gbk">GBK</option>
						<option value="gb2312">GB2312</option>
						<option value="utf8">UTF-8</option>
						<option value="iso">ISO-8859-1</option>
					</select>
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">连接时间</label>
				<div class="layui-input-inline">
					<input type="number" class="layui-input" name="connect" lay-verify="required" autocomplete="off">
				</div>
			</div>
			<div class="layui-inline">
				<label class="layui-form-label">超时时间</label>
				<div class="layui-input-inline">
					<input type="number" class="layui-input" name="socket" lay-verify="required" autocomplete="off">
				</div>
			</div>
		</div>
	</form>
</div>
<div id="content" class="layui-container" style="display: none">
	<form class="layui-form">
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">节点名称</label>
				<div class="layui-input-inline">
					<input class="layui-input" name="nName" autocomplete="off">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">请求方法</label>
				<div class="layui-input-inline">
					<select name="method">
						<option value="get">GET</option>
						<option value="post">POST</option>
					</select>
				</div>
			</div>
			<div class="layui-inline">
				<label class="layui-form-label">编码格式</label>
				<div class="layui-input-inline">
					<select name="encoding">
						<option value="gbk">GBK</option>
						<option value="gb2312">GB2312</option>
						<option value="utf8">UTF-8</option>
						<option value="iso">ISO-8859-1</option>
					</select>
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">连接时间</label>
				<div class="layui-input-inline">
					<input type="number" class="layui-input" name="connect" lay-verify="required" autocomplete="off">
				</div>
			</div>
			<div class="layui-inline">
				<label class="layui-form-label">超时时间</label>
				<div class="layui-input-inline">
					<input type="number" class="layui-input" name="socket" lay-verify="required" autocomplete="off">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<table class="layui-table">
				<colgroup>
					<col width="100">
					<col width="450">
					<col width="150">
					<col width="100">
				</colgroup>
				<thead>
				<tr>
					<th>变量名称</th>
					<th>变量值</th>
					<th>描述</th>
				</tr>
				</thead>
				<tbody id="contentBody" shape="variable">
				<tr>
					<td>
						<input type="text" class="layui-input" value="url" disabled/>
					</td>
					<td>
						<input type="text" class="layui-input" />
					</td>
					<td>
						<input type="text" class="layui-input" />
					</td>
				</tr>
				</tbody>
			</table>
		</div>
	</form>
</div>
<div id="nodeVar" class="layui-container" style="display: none">
	<form class="layui-form">
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">节点名称</label>
				<div class="layui-input-inline">
					<input class="layui-input" name="nName">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<table class="layui-table">
				<colgroup>
					<col width="100">
					<col width="450">
					<col width="150">
					<col width="100">
				</colgroup>
				<thead>
				<tr>
					<th>变量名称</th>
					<th>变量值</th>
					<th>描述</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody id="varBody" shape="variable">
				<tr>
					<td>
						<input type="text" class="layui-input" />
					</td>
					<td>
						<input type="text" class="layui-input" />
					</td>
					<td>
						<input type="text" class="layui-input" />
					</td>
					<td>
						<a  onclick="delRow(this)" class="layui-btn layui-btn-xs layui-btn-danger">删除</a>
					</td>
				</tr>
				</tbody>
			</table>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">
					<a onclick="active.addVar(this)" href="#" class="layui-btn" data-method="addVar">添加一个变量</a>
				</label>
			</div>
		</div>
	</form>
</div>
<div id="nodeOutput" class="layui-container" style="display: none">
	<form class="layui-form">
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">节点名称</label>
				<div class="layui-input-inline">
					<input class="layui-input" name="nName">
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">输出方式</label>
				<div class="layui-input-inline">
					<input type="checkbox" name="style[dialog]"  title="对话框" value="dialog" lay-skin="primary">
					<input type="checkbox" name="style[database]" title="数据库" value="database" lay-skin="primary" lay-filter="database">

				</div>
			</div>
			<div class="layui-inline" id="dataSource" style="display: none">
				<label class="layui-form-label">选择数据库</label>
				<div class="layui-input-inline" style="width: 140px">
					<select name="database"  lay-filter="database">

					</select>
				</div>
				<div class="layui-input-inline" style="width: 120px">
					<select name="tableName" lay-filter="tableName">

					</select>
				</div>
			</div>
		</div>
		<div class="layui-form-item">
			<table class="layui-table" lay-filter="outTable">
				<colgroup>
					<col width="150">
					<col width="150" class="tbStyle">
					<col width="400">
					<col width="150">
				</colgroup>
				<thead>
				<tr>
					<th>输出项</th>
					<th class="tbStyle">对应列名</th>
					<th>输出值</th>
					<th>操作</th>
				</tr>
				</thead>
				<tbody id="outBody" shape="output">
				<tr>
					<td  width="100">
						<input type="text" class="layui-input" />
					</td>

					<td width="100" class="tbStyle">
						<input type="text" class="layui-input" placeholder="请输入列名"/>
					</td>

					<td>
						<input type="text" class="layui-input" />
					</td>
					<td>
						<a onclick="delRow(this)" class="layui-btn layui-btn-xs layui-btn-danger">删除</a>
					</td>
				</tr>
				</tbody>
			</table>
		</div>
		<div class="layui-form-item">
			<div class="layui-inline">
				<label class="layui-form-label">
					<a onclick="active.addOut(this)" href="#" class="layui-btn" data-method="addOut">添加一个输出项</a>
				</label>
			</div>
		</div>
	</form>
</div>
</body>
</html>
